<?php
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type");
$root=preg_replace("/^(.*(yunshop|shante)).*$/Uisx","\\1",getcwd());
require_once("{$root}/myzhuaqu.php");
require_once("{$root}/vendor/autoload.php");

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\WebDriverExpectedCondition;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverWait;

if(preg_match("/shante\.me/Uisx",$_REQUEST['url'])) {
    if(isset($data_post)&&$data_post["s_cookie"]!=""){
        $cookiestr=$data_post["s_cookie"];
    }elseif($_REQUEST['cookie']!=""){
        $cookiestr=$_REQUEST['cookie']=trim(preg_replace("/cookie:\s*/i","",$_REQUEST['cookie']));
        file_put_contents("d:/wwwroot/www/shop/yunshop/cookie/1688.txt",$_REQUEST['cookie']);
    }else {
        $cookiestr=file_get_contents("d:/wwwroot/www/shop/yunshop/cookie/1688.txt");
    }
    $url = $_REQUEST['url'];
    $odata=getShanteItem($url,$cookiestr);
    $data = array();
    if(!empty($odata['data'])) {
        $data['base'] = $odata['globalData']['tempModel'];
        $data['sku'] = $odata['globalData']['skuModel'];
        $data['number']=$data['base']['offerId'];
        $data['summary']=$data['base']['summary'];
        $data['companyName']=$data['base']['companyName'];
        $data['sitehomeurl']=$data['base']['winportUrl'];
        $data['offerUnit']=$data['base']['offerUnit'];
        $data['name']=$data['base']['offerTitle'];
        $cateforyarr=categorytrees($data['name']);
        $cateforyarr2=categorytrees($data['name'],2);
        $cateforyarr3=categorytrees($data['name'],3);
        $cateforyarr4=categorytrees($data['name'],4);
        $cc=explode(",",$cateforyarr[count($cateforyarr)-1]["trees"]);
        $data['cid_1']=$cc[0];
        $data['cid_2']=$cc[1];
        $data['cid_3']=$cc[2];

        $temp['price']=0;
        $oldprice=0;
        foreach($data['sku']['skuInfoMapOriginal'] as $k=>$v) {
            $temp=array();
            $temp['spc_code']= $v["specAttrs"];
            $temp['price']= $v["price"];
            $temp['quantity']= 0;
            $temp['saleCount']= $v["saleCount"];
            $temp['skuId']= $v["skuId"];
            $temp['specId']= $v["specId"];
            $data['sku_spec'][] = $temp;
            if($temp['price']<$oldprice||$oldprice===0){
                //找出最高价格
                $currSku=$temp;
                $oldprice=$temp['price'];
                $data["currSku"]=$currSku;
            }
        }


        foreach ($odata['data'] as $k => $v) {
            //商品介绍
            if ($v['componentType'] == "@ali/tdmod-od-pc-offer-description") {
                $detailUrl = $v['data']['detailUrl'];
                $nr2 = file_get_contents($detailUrl);
                preg_match("/var\s+offer_details=(.*\})\;/", $nr2, $nndetail);
                $d = json_decode($nndetail[1], 1);
                $data['intro'] = $d['content'];
            }
            if ($v['componentType'] == "@ali/tdmod-od-pc-offer-tab") {
                $data['yijiandaifaurl']=searchArray($v['data']['sceneList'],array("sceneName"=>"一件代发"),"url");
            }
            if ($v['componentType'] == "@ali/tdmod-pc-od-main-pic") {
                //图片处理
                $thumbs=$v['data']['offerImgList'];
                $uploadImgTemlate="<div style=\"display: none;\"></div>";
                for($i=0;$i<count($thumbs)&&$i<3;$i++){
                    $data2=array();
                    $dir="/Uploads/Shop/Picture/".date("Y-m-d");
                    if(!preg_match("/\.(jpg|jpeg|png|titf|gif)/i",$thumbs[$i],$nn)){
                        $nn[0]=".jpg";
                    }
                    $filename=substr(md5($thumbs[$i]),0,13).$nn[0];
                    if(!file_exists($_SERVER['DOCUMENT_ROOT'].$dir."/".$filename)) {
                        createdir($_SERVER['DOCUMENT_ROOT'].$dir."/");
                        $content = file_get_contents($thumbs[$i]);
                        file_put_contents($_SERVER['DOCUMENT_ROOT'] . $dir . "/" . $filename, $content);
                    }
                    $data2['path']=$dir."/".$filename;
                    $data2['md5']=md5($data2['path']);
                    $data2['sha1']=sha1($data2['path']);
                    $data2['status']=4;
                    $data2['create_time']=time();
                    $id=insertupdate("jipu.jipu_picture",$data2,"select id from jipu.jipu_picture where md5='{$data2['md5']}'");
                    $uploadImgTemlate.="      <div class=\"upload-pre-item\" id=\"item_{$id}\">
        <input type=\"hidden\" name=\"images[]\" value=\"{$id}\" class=\"icon\" />
        <img src=\"{$data2['path']}\" data-id=\"{$id}\"/>
        <span class='btn-close delPic' title='删除图片'></span>
      </div>";
                }

                $data['video_url']=$v['data']['video']['videoUrl'];
                $data['video_cover']=$v['data']['video']['coverUrl'];
                $data['video_title']=$v['data']['video']['title'];
            }

            if ($v['componentType'] == "@ali/tdmod-od-pc-offer-logistics") {
                $data['logistics_City']=$v['data']['location'];
                $data['logistics_unitWeight']=$v['data']['unitWeight'];
                $data['logistics_unit']=$v['data']['unit'];
                $data['logistics_price']=$v['data']['price'];
                $data['logistics_label']=$v['data']['deliveryLimitText'];
            }
            if ($v['componentType'] == "@ali/tdmod-od-pc-offer-title") {
                souji($data, $v['data'], "title,unit,saleNum,saleCountDate,labels", "alibaba1688");
            }
//            if ($v['componentType'] == "@ali/tdmod-od-pc-offer-service") {
//                souji($data, $v['data'], "guaranteeList", "alibaba1688");
//            }

            //商品图片和视频链接
            if ($v['componentType'] == "@ali/tdmod-pc-od-main-pic") {
                souji($data, $v['data'], "offerImgList,video.videoUrl", "alibaba1688");
            }
            if ($v['componentType'] == "@ali/tdmod-od-gyp-pc-offer-cpv") {
                souji($data, $v['data'], "[name,value]:lable", "alibaba1688");
            }

            if ($v['componentType'] == "@ali/tdmod-od-fx-pc-offer-price") {
                $data["currSku"]["price"]=$v["data"]["jxhyRetailPriceModel"]["currentPrices"][1]["price"];
            }

            //商品属性
            if ($v['componentType'] == "@ali/tdmod-od-pc-attribute-new") {
                souji($data, $v['data'], "name,value", "alibaba1688","attribute");
            }

            //商品规格
            $index2=0;
            $strg="";
            for($i=0;$i<count($data["sku"]["skuProps"]);$i++){
                $index2++;
                $strgg="<div class=\"form-item\">
			    <label class=\"item-label label-spc\">{$data["sku"]["skuProps"][$i]["prop"]}</label>
					<div class=\"controls\">";
                $index3=0;
                for($j=0;$j<count($data["sku"]["skuProps"][$i]["value"]);$j++) {
                    $index3++;
                    $prop=substr(md5($data["sku"]["skuProps"][$i]["prop"]),0,6);
                    $en=fanyiyangjc($data["sku"]["skuProps"][$i]["prop"]);
                    $strgg .= "<label class=\"checkbox sku-item\">
							<input type=\"checkbox\" id=\"property-{$en}-{$index3}-{$prop}\" name=\"property[{$index2}][{$en}][{$prop}]\" class=\"spc_checkbox spc_1\" checked value=\"{$data["sku"]["skuProps"][$i]["value"][$j]["name"]}\" title=\"{$data["sku"]["skuProps"][$i]["value"][$j]["name"]}\">
							<label class=\"label-name\" for=\"property-{$en}-{$index3}-{$prop}\">{$data["sku"]["skuProps"][$i]["value"][$j]["name"]}</label>
						</label>";
                }
                $strgg.="	</div>		
				</div>";
                $strg.=$strgg;
            }
            $data["sku_spec"]=$strg;
        }
    }
    if(!empty($data["attribute"])) {
        for ($i = 0; $i < count($data["attribute"]); $i++) {
            if ($data["attribute"][$i]["cname"] == "品牌") {
                $data["brand"] = $data["attribute"][$i]["valuestore"];
                $d3 = array();
                $d3['name'] = $data["brand"];
                $d3['letter'] = "h";
                $d3['cid'] = $data['cid_3'];
                $d3['status'] = 1;
                $d3['store_id'] = 1;
                $r = insertupdate("jipu.jipu_brand", $d3, "select id from jipu.jipu_brand where name='{$d3['name']}'");
                $data["brand_id"] = $r;
            }
            if ($data["attribute"][$i]["cname"] == "产地") {
                $data["producing_area"] = $data["attribute"][$i]["valuestore"];
            }
            if ($data["logistics_unitWeight"] === 0 && $data["attribute"][$i]["cname"] == "重量") {
                $data["logistics_unitWeight"] = $data["attribute"][$i]["valuestore"];
            }

        }
    }
    $data['uploadImgTemlate']=$uploadImgTemlate;
    $data['cookie']=$_REQUEST['cookie'];
    $r=getrow("select sc.id,sc.name from jipu.jipu_store_class sc inner join jipu.jipu_item_category ic on ic.name=sc.name where ic.id='{$data['cid_1']}'");
    $data['store_class_id']=$r['id'];
    $data['store_class']=$r['name'];

    //补充字段
    $data['buchongzhiduan']=buchongzhiduan($data,"id,uid,supplier_id,store_id,store_cid,brand_id,cid_1,cid_2,cid_3,cid_1_dy,cid_2_dy,cid_3_dy,cid_4_dy,cid_5_dy,cid_1_sph,cid_2_sph,cid_3_sph,cid_4_sph,cid_5_sph,cid_1_xiap,cid_2_xiap,cid_3_xiap,cid_4_xiap,category,category2,category3,name,subname,summary,intro,number,price,mprice,gprice,zprice,zlprice,ztprice,ztrate,zbyprice,dqkdh,stock,weight,item_label,delivery_id,credit,coupon,tag,is_top,is_new,is_hot,is_promote,is_recommend,status,is_set_image,is_lock,thumb,images,viewnum,favnum,buynum,sort,sdp_type,sdp,sdp1,sdp2,sdp3,quota_hours,quota_num,create_time,update_time,freight,transport_id,set_zone");
    $data['cateforyarr']=$cateforyarr;
    $data['cateforyarr2']=$cateforyarr2;
    $data['cateforyarr3']=$cateforyarr3;
    $data['cateforyarr4']=$cateforyarr4;

    //修整字段
    //库存不能为0
    if($data['stock']==""){
        $data['stock']=1;
    }
    if($data['weight']==""){
        $data['weight']=0.2;
    }
    if($data['ztrate']==""){
        $data['ztrate']=0.2;
    }
    if($data['zbyprice']==""){
        $data['zbyprice']=10;
    }
    if($data['dqkdh']==""){
        $data['dqkdh']=1;
    }
    $url=preg_replace("/\/id\/[0-9]+.*$/Uisx",".html",$data_post['url']);
    $r=query("SELECT id,jspath,`type`,`value`,url  FROM jipu.`jipu_collect` WHERE url='{$url}'");//
    $content="";
    for ($i = 0; $i < count($r); $i++) {
        if(substr($r[$i]['type'],0,2)=="v_") {
            $content .= template($r[$i]['type'],$data);
        }
    }
    $data["shante_script"]=$content;
    file_put_contents("click.js",$content);
    $callback = isset($_GET['callback'])? $_GET['callback'] : '';
    if($callback){
        echo $callback. '('. json_encode($data). ')';
    }else{
        echo json_encode($data);
    }

}else{
    $data['code']=0;
    $data['msg']="不是支持的商品页面！目前支持阿里妈妈1688、淘宝、小红书、抖音小店的商品面抓取。";
    $callback = isset($_GET['callback'])? $_GET['callback'] : '';
    if($callback){
        echo $callback. '('. json_encode($data). ')';
    }else{
        echo json_encode($data);
    }
}

function getShanteItem($url,$cookiestr){
    $odata="{}";
    if(preg_match("/shop\.shante\.me\/Shop\/Item\/edit\/id\/([0-9]+)\.html/i",$url,$nn)) {
        $item_id = $nn[1];
    }
    if(preg_match("/shop\.shante\.me\/Item\/detail\/id\/([0-9]+)\.html/i",$url,$nn)) {
        $item_id = $nn[1];
    }
    if($item_id>0) {
        $data=getrow("select * from jipu.jipu_item where id ='{$item_id}'");
        $odata = json_decode($data, 1);
    }
    return $odata;
}
